const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        console.log("中间件");

        //校验token是否有效

        //1.排除不需要校验的接口
        let writePath = ['/api/login'];  
        if(writePath.includes(ctx.path)){
            await next()
        }else{
            console.log(ctx.get('token'));
            let token = ctx.get('token');
            if(token){
                try{
                    jwt.verify(token,'lixd');
                    await next();
                }catch(e){
                    if(e.name === 'JsonWebTokenError' || e.name === 'TokenExpiredError'){
                        ctx.status = 401;  //状态码
                        ctx.body = {
                            code:4,
                            msg:e
                        }
                    }else{
                        ctx.body = {
                            code:0,
                            msg:e
                        }
                    }
                }
            }else{
                ctx.body = {
                    code:4,
                    msg:'鉴权失败'
                }
            }
        }
    }
}